//引入express模块
var express = require('express');
//创建APP
var app = express();
//创建Server
var server = require('http').createServer(app);
//引入body-parser用来接收post请求的数据
var bodyParser = require('body-parser');
//引入MD5加密模块
var md5 = require('./md5');
//引入用户数据源
var users = require('./datasource/user');
//引入员工数据
var employees = require('./datasource/employee');
//引入角色数据
var roles = require('./datasource/role');
//引入PATH
var path = require('path');
//引入Multer模块（文件上传）
var multer = require('multer');
//引入文件模块fs
var fs = require('fs');
//引入rimraf模块用来删除文件和文件夹
var rimraf = require('rimraf');

//photo:就是页面传过来的那个文件的name,1代表最多能传1个
app.use(multer({ dest: 'tmp' }).array('photo', 1));

//解析POST数据
app.use(bodyParser.urlencoded({ extended: true }))

//托管静态文件
app.use(express.static(__dirname + '/src'));

//网站的入口
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/src/pages/index.html');
})

//登录
app.post('/login.do', (req, res) => {
  let username = req.body.username;
  let password = md5(req.body.password);

  if (!username || !password) {
    res.send('fail');
    return;
  }

  for (u of users) {
    if (u.username === username && u.password === password && u.state == 1) {
      res.send('success');
      return;
    }
  }
  res.send('fail');
})

//查询用户列表
app.get('/users.do', (req, res) => {
  res.send(users);
})

//查询所有角色

app.get('/roles.do', (req, res) => {
  res.send(roles);
})

app.get('/emoloyee.do', (req, res) => {
  res.send(employees);
})

//添加
app.post('/saveEmployee.do', (req, res) => {
  let filename;
  if (req.files && req.files.length > 0) {
    var file = req.files[0];
    filename=file.originalname;
    //获取原始文件的名字
    var url = __dirname + '/src/assets/img/' + file.originalname;
    //读取数据
    var data = fs.readFileSync(file.path);

    fs.writeFile(url, data, function (err) {
      if (err) {
        console.error(err);
      }
      //清除tmp临时文件夹里的内容
      rimraf(__dirname + '/tmp/*', (error) => {
        if (error) {
          console.error(error);
        }
      })
    })
  }

  let em = {
    name: req.body.name,
    age: req.body.age,
    sex: req.body.sex,
    phone: req.body.phone,
    idCard: req.body.idCard,
    role: req.body.role,
    photo: filename || req.body.photo
  }
  if (req.body.id) {
    //修改员工，ID是从页面传递过来的
    em.id = req.body.id;
    for (let i = 0; i < employees.length; i++) {
      if (employees[i].id == em.id) {
        employees[i] = em;
        break;
      }
    }
  } else {
    //新增员工，ID是后台生成的
    let id = employees[employees.length - 1].id + 1;
    em.id = id;
    console.log(em);
    employees.push(em);
  }
  res.send('success');
})


//删除员工
app.post('/remove_employee.do', (req, res) => {
  let id = req.body.id;
  for (let index = 0; index < employees.length; index++) {
    let value = employees[index];
    if (value.id == id) {
      //先删除图片
      let url = __dirname + '/src/assets/img/' + value.photo;
      try {
        fs.unlinkSync(url);
      } catch (error) {
        fs.appendFile(__dirname + '/log/error.txt', error.message, (err) => {
          if (err) throw err;
        });
        res.send('fail');
        return;
      }
      //再从数组里删除这个人
      employees.splice(index, 1);
      res.send('success');
      return;
    }
  }
  res.send('fail');
})

//重置用户密码
app.post('/resetPass.do', (req, res) => {
  let id = req.body.id;
  let new_pass = req.body.password;
  for (u of users) {
    if (u.id == id) {
      u.password = md5(new_pass);
      res.send('success');
      return;
    }
  }
  res.send('fail');
})

//修改用户状态(1:正常；0:冻结)
app.post('/change_state.do', (req, res) => {
  let id = req.body.id;
  let state = req.body.state;
  for (u of users) {
    if (u.id == id) {
      u.state = state;
      res.send('success');
      return;
    }
  }
  res.send('fail');
})

/**
 * 添加新用户
 */
app.post('/addUser.do', (req, res) => {
  let username = req.body.username;
  let password = md5(req.body.password);
  let phone = req.body.phone;
  let id = users[users.length - 1].id + 1;
  let state = 1;
  users.push({
    username, password, phone, id, state
  })
  res.send('success');
})


//根据员工ID查找这个员工的详细信息
app.get('/queryEmployeeById.do', (req, res) => {
  let id = req.query.id;
  //filter:数组过滤方法，根据函数里面的判断来返回一个新数组
  let newArr = employees.filter(value => {
    return value.id == id;
  })
  console.log(newArr);
  res.send(newArr[0]);
})

server.listen(8000);
console.log('=====Hotel Manage Startup Success in 8000=====');
